package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;

@Service
public class UserService extends LogicService<UserDao, User, Long> {
    @Autowired
    private JwtUtils jwtUtils;
    
    public UserService(@Autowired UserDao dao) {
        super(dao);
    }
    
    public Map<String, Object> login(String username, String password) throws LoginException {
        User user = dao.findByUsername(username)
                .orElseThrow(() -> new LoginException("用户名或密码错误"));
        
        if (!user.getPassword().equals(password)) {
            throw new LoginException("用户名或密码错误");
        }
        
        if (!user.isEnabled()) {
            throw new LoginException("账号已被禁用");
        }
        
        // 更新最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        dao.save(user);

        // 生成token
        String roles = String.join(",", user.getRoles());
        String token = jwtUtils.generateToken(username, roles);

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);
        return result;
    }
    
    public User register(User user) throws Exception {
        // 检查用户名是否已存在
        Optional<User> existingUser = dao.findByUsername(user.getUsername());
        if (existingUser.isPresent()) {
            throw new Exception("用户名已存在");
        }
        
        // 设置默认角色
        if (user.getRoles() == null) {
            user.setRoles(new HashSet<>());
        }
        user.getRoles().add("ROLE_USER");
        
        // 保存用户
        return dao.save(user);
    }
}
